package com.zingrow.web.jms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zingrow.common.utils.StringUtil;
import com.zingrow.web.configure.iformation.model.Iformation;
import com.zingrow.web.configure.iformation.service.IIformationService;
import com.zingrow.web.push.baidu.model.PushMessageModel;
import com.zingrow.web.push.baidu.model.UserAppModel;
import com.zingrow.web.push.baidu.service.IAppPushService;
import com.zingrow.web.push.bind.model.Bind;
import com.zingrow.web.push.bind.response.BindResponse;
import com.zingrow.web.push.bind.service.IBindService;
import com.zingrow.web.report.model.RptInfo;
import com.zingrow.web.report.response.UserResp;
import com.zingrow.web.report.service.IRptInfoService;
import com.zzyq.dataManager.bean.MessageText;

@Component
public class Receiver implements MessageListener {
	private static Logger logger = LoggerFactory.getLogger(JMSProducer.class);

	@Autowired
	private IIformationService iformationService;

	@Autowired
	private IBindService bindService;

	@Autowired
	private IAppPushService appPushService;

	@Autowired
	private IRptInfoService rptInfoService;

	private static final int versionNumber = 310;// APP报告版本序列号

	@Override
	public void onMessage(Message message) {
		try {
			// 从服务器获取消息
			MessageText text = (MessageText) ((ObjectMessage) message).getObject();
			// System.out.println(text);
			// 推送报告
			if (text.getType() == 1) {
				// 得到用户
				List<RptInfo> UserRptlist = new ArrayList<>();
				UserRptlist = rptInfoService.selectUserRptById(text.getRepId());// 接口中增加了用户权限条件，所以得到的是有报告权限的用户
				if (UserRptlist.size() > 0) {
					List<UserResp> UserRespList = UserRptlist.get(0).getUsers();
					// 循环对应用户
					for (UserResp userResp : UserRespList) {
						// 判断版本
						Integer i = bindService.selectAppVerSionNumberByUserName(userResp.getUserName());
						if (i != null && i >= versionNumber) {
							// 推送
							Bind bind = bindService.selectAppByUserName(userResp.getUserName());
							if (bind != null) {
								UserAppModel userAppModel = new UserAppModel();
								userAppModel.setAppDeviceType(bind.getBaidu_app_type());
								userAppModel.setAppChannelId(bind.getBaidu_channel_id());
								userAppModel.setAppId(bind.getBaidu_app_id());
								if (userAppModel.getAppDeviceType() == 4) {
									if (null == bind.getBadge()) {
										bind.setBadge(0);
									}

									userAppModel.setBadge(bind.getBadge() + 1);
								}
								Set<UserAppModel> set = new HashSet<>();
								set.add(userAppModel);
								PushMessageModel pushMessageModel = new PushMessageModel();
								pushMessageModel.setTitle(text.getTitle());
								Map<String, String> contentMap = new HashMap<>();
								contentMap.put("articleId", "0");
								contentMap.put("ifmId", "0");
								contentMap.put("repId", text.getRepId().toString());
								contentMap.put("moduleSort", text.getModuleSort());
								contentMap.put("type", text.getType().toString());
								pushMessageModel.setContentMap(contentMap);
								if (appPushService.pushNoticeMessage(set, pushMessageModel) > 0) {
									int appType = bind.getBaidu_app_type();
									String appTypeStr = "";
									switch (appType) {
									case 3:
										appTypeStr = "安卓";
										break;
									case 4:
										appTypeStr = "IOS";
										break;
									}
									logger.info(String.format("用户名:%s,手机类型：%s,报告id:%s,标题:%s 提交百度云操作完成！",
											bind.getUser_account(), appTypeStr, text.getRepId().toString(),
											text.getTitle()));
									if (userAppModel.getAppDeviceType() == 4) {
										bind.setBadge(bind.getBadge() + 1);
										bindService.modifyBadge(bind);
									}
								}
							} else {
								logger.info("报告" + text.getTitle() + "并没有找到关联的用户，无法提交百度云！");
							}
						} else {
							logger.info("用户" + userResp.getUserName() + "使用的APP版本低于中周报告版本，不予提交百度云推送！");
						}
					}
				}
			} else if (text.getType() == 0) {
				// 推送信息
				// 获取消息中的方案ID
				Integer ifm_id = Integer.parseInt(text.getIfmId());
				try {
					if (StringUtils.isNotBlank(ifm_id.toString())) {
						// 查看此方案在后台配置中是否设置为需要推送
						Iformation iformation = iformationService.queryByID(ifm_id);
						iformation.getIfm_id();// 捕获异常所用
						if (null != iformation) {
							if (iformation.getIfm_pushed() == null) {
								logger.info("后台设置的方案是否推送字段为NULL，无法判断是否推送！");
							} else {
								// 如果需要推送
								if (iformation.getIfm_pushed() == 1) {
									// ---------------------------------------根据组织——用户——方案推送逻辑----------------------------
									// 先找到方案对应的用户和绑定信息
									List<BindResponse> bindResponseList = bindService.selectAppUser(ifm_id);
									if (bindResponseList.size() <= 0) {
										logger.info("此消息并没有找到关联的用户，无法推送！");
									} else {
										// 验证方案ID在不在这写用户之中
										for (BindResponse bindResponse : bindResponseList) {
											String RopeProgramme = bindResponse.getRopeProgramme();// 用户所拥有方案ID
																									// 逗号分隔形式
											// 分隔这个字段
											if (StringUtils.isNotBlank(RopeProgramme)) {
												List<String> str = StringUtil.toStringTokenizer(RopeProgramme, ",");
												for (String ifmId : str) {
													if (ifmId.equals(ifm_id.toString())) {// 此用户有这个方案
														// 执行推送并跳过这层对比循环
														UserAppModel userAppModel = new UserAppModel();
														userAppModel.setAppDeviceType(bindResponse.getBaidu_app_type());
														userAppModel
																.setAppChannelId(bindResponse.getBaidu_channel_id());
														userAppModel.setAppId(bindResponse.getBaidu_app_id());
														if (userAppModel.getAppDeviceType() == 4) {
															if (null == bindResponse.getBadge()) {
																bindResponse.setBadge(0);
															}

															userAppModel.setBadge(bindResponse.getBadge() + 1);
														}
														Set<UserAppModel> set = new HashSet<>();
														set.add(userAppModel);
														PushMessageModel pushMessageModel = new PushMessageModel();
														pushMessageModel.setTitle(text.getTitle());
														Map<String, String> contentMap = new HashMap<>();
														contentMap.put("articleId", text.getArticleId());
														contentMap.put("ifmId", text.getIfmId());
														contentMap.put("type", "0");
														pushMessageModel.setContentMap(contentMap);
														if (appPushService.pushNoticeMessage(set,
																pushMessageModel) > 0) {
															int appType = bindResponse.getBaidu_app_type();
															String appTypeStr = "";
															switch (appType) {
															case 3:
																appTypeStr = "安卓";
																break;
															case 4:
																appTypeStr = "IOS";
																break;
															}
															logger.info(String.format(
																	"用户名:%s,手机类型：%s,方案id:%s,文章id:%s,标题:%s 提交百度云操作完成！",
																	bindResponse.getUser_account(), appTypeStr, ifm_id,
																	text.getArticleId(), text.getTitle()));
															if (userAppModel.getAppDeviceType() == 4) {
																bindResponse.setBadge(bindResponse.getBadge() + 1);
																bindService.modifyBadge(bindResponse);
															}
														}
														break;
													}
												} // 循环对比结束
											} // 字段不为空结束
										} // 验证结束
									}
									// ---------------------------------------根据组织——用户——方案推送逻辑----------------------------

									// ----------------------------------------根据组织推送逻辑-----------------------------
									// // 查看此消息推送的对应用户集合
									// List<Bind> bindList =
									// bindService.selectAppByifmId(ifm_id);
									// if (bindList.size() <= 0) {
									// logger.info("此消息并没有找到关联的用户，无法推送！");
									// } else {
									// // 推送
									// for (Bind bind : bindList) {
									// UserAppModel userAppModel = new
									// UserAppModel();
									// userAppModel.setAppDeviceType(bind.getBaidu_app_type());
									// userAppModel.setAppChannelId(bind.getBaidu_channel_id());
									// userAppModel.setAppId(bind.getBaidu_app_id());
									// if (userAppModel.getAppDeviceType() == 4)
									// {
									// if (null == bind.getBadge()) {
									// bind.setBadge(0);
									// }
									//
									// userAppModel.setBadge(bind.getBadge() +
									// 1);
									// }
									// Set<UserAppModel> set = new HashSet<>();
									// set.add(userAppModel);
									// PushMessageModel pushMessageModel = new
									// PushMessageModel();
									// pushMessageModel.setTitle(text.getTitle());
									// Map<String, String> contentMap = new
									// HashMap<>();
									// contentMap.put("articleId",
									// text.getArticleId());
									// contentMap.put("ifmId", text.getIfmId());
									// contentMap.put("type", "0");
									// pushMessageModel.setContentMap(contentMap);
									// if (appPushService.pushNoticeMessage(set,
									// pushMessageModel) > 0) {
									// int appType = bind.getBaidu_app_type();
									// String appTypeStr = "";
									// switch (appType) {
									// case 3:
									// appTypeStr = "安卓";
									// break;
									// case 4:
									// appTypeStr = "IOS";
									// break;
									// }
									// logger.info(String.format("用户名:%s,手机类型：%s,方案id:%s,文章id:%s,标题:%s
									// 提交百度云操作完成！",
									// bind.getUser_account(), appTypeStr,
									// ifm_id, text.getArticleId(),
									// text.getTitle()));
									// if (userAppModel.getAppDeviceType() == 4)
									// {
									// bind.setBadge(bind.getBadge() + 1);
									// bindService.modifyBadge(bind);
									// }
									// }
									// }
									// }
									// ----------------------------------------根据组织推送逻辑-----------------------------
								}
							}
						}
					}
				} catch (NullPointerException e) {
					logger.info("推送的方案id：" + ifm_id + "信息存在数据问题！");
				}
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
